<script setup lang="ts">
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
import { ref, watch } from 'vue'

export interface Todo {
  id: number
  content: string
  done: boolean
}
// 数据初始化，优先从本地存储中获取
const list = ref<Todo[]>(JSON.parse(localStorage.getItem('todo-list') || '[]'))

// 修改任务状态功能
const changeDone = (id: number) => {
  const todo = list.value.find((item) => item.id === id)
  if (todo) {
    todo.done = !todo.done
  }
}

// 删除功能
const delTodo = (id: number) => {
  list.value = list.value.filter((item) => item.id !== id)
}

// 添加功能
const addTodo = (content: string) => {
  list.value.unshift({
    id: Date.now(),
    content: content,
    done: false,
  })
}

// 修改全选状态功能
const checkAll = (isCheckAll: boolean) => {
  list.value.forEach((item) => {
    item.done = isCheckAll
  })
}

// 侦听器：list 变化，同步到本地存储
watch(
  list,
  () => {
    localStorage.setItem('todo-list', JSON.stringify(list.value))
  },
  // 开启深度侦听
  { deep: true },
)
</script>

<template>
  <section class="todoapp">
    <TodoHeader @add-todo="addTodo" />
    <TodoMain
      :list="list"
      @change-done="changeDone"
      @del-todo="delTodo"
      @check-all="checkAll"
    />
    <TodoFooter :list="list" />
  </section>
</template>
